package com.rabbit.mq.impl;

import com.rabbit.config.MqProducerProperties;
import com.rabbit.entity.Device;
import com.rabbit.entity.Room;
import com.rabbit.entity.User;
import com.rabbit.mq.SyncDirectProducer;
import com.rabbit.route.RoutingKey;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yuhuan
 * @date 2025/4/18
 */
@Service
public class SyncDirectProducerImpl implements SyncDirectProducer {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MqProducerProperties mqProperties;

    @Override
    public void sendUserSyncMessage(User message) {
        message.setId("1");
        System.out.println(String.format("正在发送用户消息[%s]，msg: %s", message.getName(), message));
        CorrelationData callbackMsgId = new CorrelationData(String.format("用户：%s", message.getId()));
        // 消息默认是持久化的
        rabbitTemplate.convertAndSend(mqProperties.getSyncExchangeName(), RoutingKey.MQ_KEY_USER, message, callbackMsgId);
    }

    @Override
    public void sendRoomSyncMessage(Room message) {
        message.setId("2");
        System.out.println(String.format("正在发送房间消息[%s]，msg: %s", message.getName(), message));
        rabbitTemplate.convertAndSend(mqProperties.getSyncExchangeName(), RoutingKey.MQ_KEY_ROOM, message, m -> {
            // 设置消息为非持久化模式
            m.getMessageProperties().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
            return m;
        });
    }

    @Override
    public void sendDeviceSyncMessage(Device message) {
        message.setId("3");
        System.out.println(String.format("正在发送设备消息[%s]，msg: %s", message.getName(), message));
        rabbitTemplate.convertAndSend(mqProperties.getSyncExchangeName(), RoutingKey.MQ_KEY_DEVICE, message);
    }
}
